package com.wwp.tbshop.view.fragment.diyview;


import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wwp.tbshop.R;
import com.wwp.tbshop.activity.MainActivity;
import com.wwp.tbshop.activity.OrderSubmitActivity;
import com.wwp.tbshop.manager.FragmentFactory;
import com.wwp.tbshop.model.bean.CartQueryBean;
import com.wwp.tbshop.presenter.CartPresenter;
import com.wwp.tbshop.util.PriceFormater;
import com.wwp.tbshop.util.SPUtils;
import com.wwp.tbshop.view.adapter.CartARAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 楠GG on 2017/6/15.
 */

public class CartFragment extends Fragment {

    @Bind(R.id.recyclerview)
    RecyclerView mRecyclerview;
    @Bind(R.id.iv_empty)
    ImageView mIvEmpty;
    @Bind(R.id.rv_recommengoods)
    RecyclerView mRvRecommengoods;
    @Bind(R.id.ll_empty_shopcart)
    LinearLayout mLlEmptyShopcart;
    @Bind(R.id.checkbox_all)
    CheckBox mCheckboxAll;
    @Bind(R.id.tv_shopcart_total)
    TextView mTvShopcartTotal;
    @Bind(R.id.btn_check_out)
    Button mBtnCheckOut;
    @Bind(R.id.ll_check_all)
    LinearLayout mLlCheckAll;
    @Bind(R.id.cb_all)
    CheckBox mCbAll;
    @Bind(R.id.btn_delete)
    Button mBtnDelete;
    @Bind(R.id.btn_collection)
    Button mBtnCollection;
    @Bind(R.id.ll_delete)
    LinearLayout mLlDelete;
    @Bind(R.id.tv_goods_recommend)
    TextView mTvGoodsRecommend;
    public CartARAdapter mCartARAdapter;

    private CartPresenter mCartPresenter;
    private boolean isChecked = false;
    private int Price = 0;
    private List<CartQueryBean.CartBean> mCartBean = new ArrayList<>();
    private String mUserId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View rootView = null;
        if (!isLoading()) {
            ((MainActivity) getActivity()).changePage(FragmentFactory.createFragmentByPosition(3));
            ((MainActivity) getActivity()).mRgBottomBar.check(R.id.rb_user);
            Toast.makeText(getActivity(), "请先登录哦,亲", Toast.LENGTH_SHORT).show();
        } else {
            rootView = View.inflate(getActivity(), R.layout.fragment_shop, null);
            ButterKnife.bind(this, rootView);
            mCartPresenter = new CartPresenter(this);

            mCartARAdapter = new CartARAdapter(getActivity(), mCartPresenter, this);
            mRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
            mRecyclerview.setAdapter(mCartARAdapter);
        }
        return rootView;

    }

    @Override
    public void onResume() {
        super.onResume();
        if(mCartPresenter!=null){
            mCartPresenter.getQuryInfo(mUserId);
            mCartARAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //TODO:userId数据
        if (mCartPresenter != null) {
            mCartPresenter.getQuryInfo(mUserId);

            //全选的动作
            mCheckboxAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isChecked = !isChecked;
                    if (isChecked) {
                        mCheckboxAll.setChecked(true);
                        for (CartQueryBean.CartBean cartBean : mCartBean) {
                            cartBean.setChecked(true);
                            mCartARAdapter.notifyDataSetChanged();
                        }
                        updatCartInfo();
                    } else {
                        mCheckboxAll.setChecked(false);
                        for (CartQueryBean.CartBean cartBean : mCartBean) {
                            cartBean.setChecked(false);
                            mCartARAdapter.notifyDataSetChanged();
                        }

                    }
                }
            });
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.btn_check_out, R.id.btn_delete, R.id.btn_collection})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_check_out:
                if (isChecked()) {
                    Intent payIntent = new Intent(getActivity(), OrderSubmitActivity.class);
                    String sku = getSku();
                    payIntent.putExtra("sku", sku);
                    getActivity().startActivity(payIntent);
                } else {
                    return;
                }
                break;

            case R.id.btn_delete:

                break;

            case R.id.btn_collection:
                break;
        }
    }

    public void onQuerySuccess(List<CartQueryBean.CartBean> cartBeen) {
        this.mCartBean = cartBeen;

        if (mCartBean.size() == 0) {
            mLlEmptyShopcart.setVisibility(View.VISIBLE);
            mRecyclerview.setVisibility(View.GONE);
            mLlCheckAll.setVisibility(View.GONE);
            mTvGoodsRecommend.setVisibility(View.GONE);
        } else {
            mCartARAdapter.setCartBeanInfo(cartBeen);
        }

    }

    public void onUpdateSuccess(List<CartQueryBean.CartBean> updateBeen) {
        mCartARAdapter.setCartUpdateBeanInfo(updateBeen);
    }

    public void onDeleteSuccess(List<CartQueryBean.CartBean> deleteBeen) {
        mCartARAdapter.setCartDeleteBeanInfo(deleteBeen);
    }



    public void updatCartInfo() {

        float totalPrice = mCartARAdapter.countTotalPrice();
        boolean isAllChecked = mCartARAdapter.isAllChecked();
        isChecked = isAllChecked;
        if (mTvShopcartTotal != null) {
            mTvShopcartTotal.setText(PriceFormater.format(totalPrice) + "");
        }
        if (mCheckboxAll != null) {
            mCheckboxAll.setChecked(isAllChecked);
        }
    }

    public void selectAll() {
        for (CartQueryBean.CartBean cartBean : mCartBean) {
            if (!cartBean.isChecked()) {
                mCheckboxAll.setChecked(false);
                mTvShopcartTotal.setText(PriceFormater.format(0));
                return;
            }
        }
        mCheckboxAll.setChecked(true);
    }

    public boolean isChecked() {

        for (CartQueryBean.CartBean cartBean : mCartBean) {
            if (cartBean.isChecked()) {
                return true;
            }
        }
        return false;

    }

    private String getSku() {
        String sku = "";
        for (int i = 0; i < mCartBean.size(); i++) {
            CartQueryBean.CartBean infoBean = mCartBean.get(i);
            if (infoBean.isChecked()) {
                sku += infoBean.getProductId() + ":" + infoBean.getProductCount() + ":" + infoBean.getPropertyId() + "|";
                Log.d("SKU", "getSku: " + sku);
            }
        }
        return sku.substring(0, sku.length() - 1);
    }

    // 是否已登录
    public boolean isLoading() {
        mUserId = SPUtils.getUerid();
        if (TextUtils.isEmpty(mUserId)) {
            return false;
        }
        return true;
    }

}